/*
  @Author Ligg
  @Time 2025/8/12
 */

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/foundation.dart';
import 'package:media_kit/media_kit.dart';
import 'package:media_kit_video/media_kit_video.dart';
import 'package:window_manager/window_manager.dart';

/// 全屏视频播放页面
class FullscreenVideoPage extends StatefulWidget {
  const FullscreenVideoPage({super.key});

  @override
  State<FullscreenVideoPage> createState() => _FullscreenVideoPageState();
}

/// 全屏视频播放页面状态管理
class _FullscreenVideoPageState extends State<FullscreenVideoPage>
    with WindowListener {
  /// 媒体播放器实例
  late final Player _player;

  /// 视频控制器实例
  late final VideoController _videoController;

  /// 是否处于全屏状态
  bool _isFullscreen = false;

  /// 控制条是否可见
  bool _controlsVisible = true;

  /// 自动隐藏控制条的定时器
  Timer? _hideTimer;

  /// 当前播放位置
  Duration _position = Duration.zero;

  /// 视频总时长
  Duration _duration = Duration.zero;

  /// 缓冲进度时长
  Duration _buffer = Duration.zero;

  /// 拖动进度条时的临时位置
  Duration? _dragPosition;

  @override
  void initState() {
    super.initState();
    // 仅在桌面平台添加窗口监听器
    if (_isDesktop) {
      windowManager.addListener(this);
    }

    // 初始化播放器和视频控制器
    _player = Player();
    _videoController = VideoController(_player);

    // 打开视频源
    _player.open(
      Media('https://apn.moedot.net/d/wo/2507/%E6%9B%B4%E8%A1%A304z.mp4'),
    );

    // 监听播放位置变化
    _player.stream.position.listen((p) {
      if (!mounted) return;
      setState(() => _position = p);
    });
    // 监听视频总时长变化
    _player.stream.duration.listen((d) {
      if (!mounted) return;
      setState(() => _duration = d);
    });
    // 监听缓冲进度变化
    _player.stream.buffer.listen((b) {
      if (!mounted) return;
      setState(() => _buffer = b);
    });
  }

  @override
  void dispose() {
    // 清理资源
    if (_isDesktop) {
      windowManager.removeListener(this);
    }
    _hideTimer?.cancel();
    _player.dispose();
    super.dispose();
  }

  /// 设置系统UI的显示/隐藏状态
  /// [hidden] true表示隐藏系统UI，false表示显示系统UI
  Future<void> _setSystemUIHidden(bool hidden) async {
    if (defaultTargetPlatform == TargetPlatform.android) {
      // Android平台：使用immersive模式隐藏状态栏和导航栏
      if (hidden) {
        await SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersive);
      } else {
        await SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
      }
    } else if (defaultTargetPlatform == TargetPlatform.iOS) {
      // iOS平台：手动控制overlay的显示/隐藏
      if (hidden) {
        await SystemChrome.setEnabledSystemUIMode(
          SystemUiMode.manual,
          overlays: [],
        );
      } else {
        await SystemChrome.setEnabledSystemUIMode(
          SystemUiMode.manual,
          overlays: SystemUiOverlay.values,
        );
      }
    } else {
      // 其他平台（桌面/Web）：使用edgeToEdge模式
      await SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
    }
  }

  /// 设置全屏时的屏幕方向
  /// [enable] true表示启用横屏，false表示恢复所有方向
  Future<void> _setOrientationForFullscreen(bool enable) async {
    if (defaultTargetPlatform == TargetPlatform.android ||
        defaultTargetPlatform == TargetPlatform.iOS) {
      if (enable) {
        // 全屏时锁定为横屏
        await SystemChrome.setPreferredOrientations([
          DeviceOrientation.landscapeLeft,
          DeviceOrientation.landscapeRight,
        ]);
      } else {
        // 退出全屏时恢复所有方向
        await SystemChrome.setPreferredOrientations(DeviceOrientation.values);
      }
    }
  }

  /// 安排自动隐藏控制条
  /// 仅在全屏模式下生效，3秒后自动隐藏
  void _scheduleAutoHide() {
    _hideTimer?.cancel();
    if (!_isFullscreen) return; // 仅全屏自动隐藏
    _hideTimer = Timer(const Duration(seconds: 3), () {
      if (!mounted) return;
      setState(() => _controlsVisible = false);
    });
  }

  /// 进入全屏模式
  Future<void> _enterFullscreen() async {
    await _setSystemUIHidden(true); // 隐藏系统UI
    await _setOrientationForFullscreen(true); // 设置横屏
    if (_isDesktop) {
      await windowManager.setFullScreen(true); // 桌面端设置窗口全屏
    }
    setState(() {
      _isFullscreen = true;
      _controlsVisible = true;
    });
    _scheduleAutoHide(); // 安排自动隐藏
  }

  /// 退出全屏模式
  Future<void> _exitFullscreen() async {
    await _setSystemUIHidden(false); // 显示系统UI
    await _setOrientationForFullscreen(false); // 恢复屏幕方向
    if (_isDesktop) {
      await windowManager.setFullScreen(false); // 桌面端退出窗口全屏
    }
    setState(() {
      _isFullscreen = false;
      _controlsVisible = true; // 退出全屏显示控件
    });
    _hideTimer?.cancel(); // 取消自动隐藏
  }

  /// 切换全屏状态
  Future<void> _toggleFullscreen() async {
    if (_isFullscreen) {
      await _exitFullscreen();
    } else {
      await _enterFullscreen();
    }
  }

  /// 格式化时长显示
  /// 支持小时:分钟:秒 和 分钟:秒 两种格式
  String _formatDuration(Duration d) {
    final totalSeconds = d.inSeconds;
    final hours = totalSeconds ~/ 3600;
    final minutes = (totalSeconds % 3600) ~/ 60;
    final seconds = totalSeconds % 60;
    if (hours > 0) {
      return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
    }
    return '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  }

  /// 进度条最大值（毫秒）
  double get _sliderMax =>
      _duration.inMilliseconds > 0 ? _duration.inMilliseconds.toDouble() : 1.0;

  /// 进度条当前值（毫秒）
  double get _sliderValue {
    final active = _dragPosition ?? _position;
    return active.inMilliseconds.clamp(0, _duration.inMilliseconds).toDouble();
  }

  /// 缓冲进度比例（0.0 - 1.0）
  double get _bufferedFraction {
    if (_duration.inMilliseconds <= 0) return 0.0;
    final value = _buffer.inMilliseconds / _duration.inMilliseconds;
    if (value.isNaN || value.isInfinite) return 0.0;
    return value.clamp(0.0, 1.0);
  }

  /// 点击视频画面时的处理
  /// 切换控制条的显示/隐藏状态
  void _onTapSurface() {
    setState(() => _controlsVisible = !_controlsVisible);
    if (_controlsVisible) _scheduleAutoHide();
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      // 全屏时拦截返回键
      canPop: !_isFullscreen,
      onPopInvokedWithResult: (didPop, result) async {
        if (!didPop && _isFullscreen) {
          await _exitFullscreen(); // 先退出全屏
        }
      },
      child: Scaffold(
        backgroundColor: Colors.black, // 统一深色背景
        body: Stack(
          fit: StackFit.expand,
          children: [
            // 视频在顶部对齐的 16:9 容器内
            Align(
              alignment: Alignment.topCenter,
              child: AspectRatio(
                aspectRatio: 16 / 9, // 16:9 宽高比
                child: Video(controller: _videoController, controls: null),
              ),
            ),

            // 点击画面显隐控件的透明层
            Positioned.fill(
              child: GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: _onTapSurface,
              ),
            ),

            // 顶部返回按钮 - 贴边显示
            Positioned(
              top: 0,
              left: 0,
              right: 0,
              child: AnimatedOpacity(
                duration: const Duration(milliseconds: 180),
                curve: Curves.easeOut,
                opacity: _controlsVisible ? 1.0 : 0.0,
                child: Container(
                  // 渐变背景，从半透明黑色到透明
                  decoration: const BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: [Colors.black54, Colors.transparent],
                    ),
                  ),
                  child: Row(
                    children: [
                      IconButton(
                        onPressed: _exitFullscreen,
                        icon: const Icon(Icons.arrow_back),
                        color: Colors.white,
                      ),
                    ],
                  ),
                ),
              ),
            ),

            // 底部控件 - 贴边显示
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: AnimatedOpacity(
                opacity: _controlsVisible ? 1.0 : 0.0,
                duration: const Duration(milliseconds: 180),
                child: Container(
                  // 渐变背景，从透明到半透明黑色
                  decoration: const BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: [Colors.transparent, Colors.black54],
                    ),
                  ),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      // 时间信息显示
                      Row(
                        children: [
                          const SizedBox(width: 8),
                          Text(
                            '${_formatDuration(_dragPosition ?? _position)} / ${_formatDuration(_duration)}',
                            style: const TextStyle(color: Colors.white),
                          ),
                        ],
                      ),
                      // 播放控制和进度条
                      Row(
                        children: [
                          // 播放/暂停按钮
                          StreamBuilder<bool>(
                            stream: _player.stream.playing,
                            initialData: false,
                            builder: (context, snapshot) {
                              final playing = snapshot.data ?? false;
                              return IconButton(
                                onPressed: () async {
                                  if (playing) {
                                    await _player.pause();
                                  } else {
                                    await _player.play();
                                  }
                                  _scheduleAutoHide();
                                },
                                iconSize: 32,
                                icon: Icon(
                                  playing ? Icons.pause : Icons.play_arrow,
                                ),
                                color: Colors.white,
                              );
                            },
                          ),

                          // 进度条
                          Expanded(
                            child: SliderTheme(
                              data: SliderTheme.of(context).copyWith(
                                trackHeight: 3, // 轨道高度
                                thumbShape: const RoundSliderThumbShape(
                                  enabledThumbRadius: 7,
                                ), // 滑块形状
                                activeTrackColor:
                                    Colors.blue.shade400, // 已播放进度条颜色
                                inactiveTrackColor:
                                    Colors.grey.shade800, // 未播放进度条颜色
                                trackShape: _BufferedSliderTrackShape(
                                  // 自定义轨道形状，支持缓冲进度
                                  bufferedFraction: _bufferedFraction,
                                  bufferedColor: Colors.white.withValues(
                                    alpha: 0.4,
                                  ), // 更明显的缓冲条颜色
                                ),
                              ),
                              child: Slider(
                                min: 0,
                                max: _sliderMax,
                                value: _sliderValue.clamp(0, _sliderMax),
                                onChangeStart: (_) {
                                  // 开始拖动时取消自动隐藏并显示控制条
                                  _hideTimer?.cancel();
                                  setState(() => _controlsVisible = true);
                                },
                                onChanged: (v) {
                                  // 拖动过程中更新临时位置
                                  setState(
                                    () => _dragPosition = Duration(
                                      milliseconds: v.toInt(),
                                    ),
                                  );
                                },
                                onChangeEnd: (v) async {
                                  // 拖动结束时跳转到指定位置
                                  setState(() => _dragPosition = null);
                                  await _player.seek(
                                    Duration(milliseconds: v.toInt()),
                                  );
                                  _scheduleAutoHide(); // 重新安排自动隐藏
                                },
                              ),
                            ),
                          ),

                          // 全屏切换按钮
                          IconButton(
                            iconSize: 32,
                            onPressed: _toggleFullscreen,
                            icon: Icon(
                              _isFullscreen
                                  ? Icons.fullscreen_exit
                                  : Icons.fullscreen,
                            ),
                            color: Colors.white,
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// 自定义进度条轨道形状，支持显示缓冲进度
/// 绘制三段：未缓冲（半透明白）、已缓冲（浅白）、已播放（主题色）
class _BufferedSliderTrackShape extends RoundedRectSliderTrackShape {
  _BufferedSliderTrackShape({
    required this.bufferedFraction,
    required this.bufferedColor,
  });

  /// 缓冲进度比例（0.0 - 1.0）
  final double bufferedFraction;

  /// 缓冲进度条的颜色
  final Color bufferedColor;

  @override
  void paint(
    PaintingContext context,
    Offset offset, {
    required RenderBox parentBox,
    required SliderThemeData sliderTheme,
    double additionalActiveTrackHeight = 2,
    required Animation<double> enableAnimation,
    required TextDirection textDirection,
    required Offset thumbCenter,
    bool isEnabled = false,
    bool isDiscrete = false,
    Offset? secondaryOffset, // 兼容性参数，忽略
  }) {
    assert(sliderTheme.trackHeight != null);
    // 获取轨道矩形区域
    final Rect trackRect = getPreferredRect(
      parentBox: parentBox,
      sliderTheme: sliderTheme,
      isEnabled: isEnabled,
      isDiscrete: isDiscrete,
    ).shift(offset);

    final Radius radius = Radius.circular(trackRect.height / 2);

    // 1) 绘制基础未激活轨道（深灰色）
    final Paint inactivePaint = Paint()
      ..color = sliderTheme.inactiveTrackColor ?? Colors.grey.shade800;
    context.canvas.drawRRect(
      RRect.fromRectAndRadius(trackRect, radius),
      inactivePaint,
    );

    // 2) 绘制缓冲进度（浅白色）
    final double bufferedWidth =
        trackRect.width * bufferedFraction.clamp(0.0, 1.0);
    if (bufferedWidth > 0) {
      final Rect bufferRect = Rect.fromLTWH(
        trackRect.left,
        trackRect.top,
        bufferedWidth,
        trackRect.height,
      );
      final Paint bufferPaint = Paint()..color = bufferedColor;
      context.canvas.drawRRect(
        RRect.fromRectAndRadius(bufferRect, radius),
        bufferPaint,
      );
    }

    // 3) 绘制已播放进度（主题色）
    final double playedFraction =
        ((thumbCenter.dx - trackRect.left) / trackRect.width).clamp(0.0, 1.0);
    final Rect playedRect = Rect.fromLTWH(
      trackRect.left,
      trackRect.top,
      trackRect.width * playedFraction,
      trackRect.height,
    );
    final Paint activePaint = Paint()
      ..color = sliderTheme.activeTrackColor ?? Colors.blue.shade400;
    context.canvas.drawRRect(
      RRect.fromRectAndRadius(playedRect, radius),
      activePaint,
    );
  }
}

/// 判断当前是否为桌面平台（Windows、Linux、macOS）
bool get _isDesktop => const {
  TargetPlatform.windows,
  TargetPlatform.linux,
  TargetPlatform.macOS,
}.contains(defaultTargetPlatform);
